package com.spring.app.common.filters;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.text.html.HTMLDocument.Iterator;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

import com.spring.app.common.domain.DBUser;

public class RoleBasedAuthenticationFilter extends SavedRequestAwareAuthenticationSuccessHandler {
	
	private static final String ROLE_TYPE = "ROLE_PREMIUM";
	
	public void onAuthenticationSuccess(HttpServletRequest request,
										HttpServletResponse response,
										Authentication authentication) throws ServletException,IOException{
		String cntxPath = request.getContextPath();
		Object user = authentication.getPrincipal();
		request.getSession().setAttribute("currentUser",user);
		System.out.print("current user..."+((UserDetails) user).getUsername());
		if(containsPremiumMember(authentication)){
			response.sendRedirect(cntxPath+"/main/main/premium?username="+((UserDetails) user).getUsername());
		}else{
			response.sendRedirect(cntxPath+"/main/main/common?username="+((UserDetails) user).getUsername());
		}
	}
	
	private boolean containsPremiumMember(final Authentication auth) { 
        for (final GrantedAuthority grantedAuthority : auth.getAuthorities()) { 
            if (grantedAuthority.getAuthority().equals(ROLE_TYPE)) { 
                return true; 
            } 
        } 
        return false; 
    } 
	
}